package com.naiterui.ehp.bs.ds.modules.sys.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.base.Preconditions;
import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.security.annotation.SysLog;
import com.naiterui.ehp.bp.security.utils.SecurityUtils;
import com.naiterui.ehp.bp.support.exception.BaseExceptionCodes;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.ds.common.controller.AbstractController;
import com.naiterui.ehp.bs.ds.common.utils.Constant;
import com.naiterui.ehp.bs.ds.modules.sys.entity.Menu;
import com.naiterui.ehp.bs.ds.modules.sys.service.IMenuService;

import io.swagger.annotations.Api;

/**
 * 系统菜单
 */
@Validated
@Api(tags = {SwaggerTag.DS + SwaggerTag.SYS})
@RestController
@RequestMapping("/sys/menu")
public class MenuController extends AbstractController {

    @Autowired
    private IMenuService menuService;

    /**
     * 导航菜单
     *
     * @return
     */
    @SysLog("导航菜单")
    @GetMapping("/nav")
    public List<Menu> nav() {
        Long id = SecurityUtils.getCurrentUser().getId();
        return this.menuService.getUserMenuList(id);
    }

    /**
     * 所有菜单列表
     *
     * @return
     */
    @SysLog("所有菜单列表")
    @GetMapping("/list")
    @PreAuthorize("@p.check('sys:menu:list')")
    public List<Menu> list() {
        return this.menuService.queryList();
    }

    /**
     * 选择菜单(添加、修改菜单)
     *
     * @return
     */
    @SysLog("选择菜单(添加、修改菜单)")
    @GetMapping("/select")
    public List<Menu> select() {
        // 查询列表数据
        return this.menuService.queryNotButtonList();
    }

    /**
     * 菜单信息
     *
     * @return
     */
    @SysLog("获取菜单信息")
    @GetMapping("/info/{menuId}")
    @PreAuthorize("@p.check('sys:menu:info')")
    public Menu info(@PathVariable("menuId") Long menuId) {
        return this.menuService.getById(menuId);
    }

    /**
     * 保存
     */
    @SysLog("保存菜单")
    @PostMapping("/save")
    @PreAuthorize("@p.check('sys:menu:save')")
    public void save(@RequestBody Menu menu) throws BusinessException {
        // 数据校验
        this.verifyForm(menu);
        this.menuService.save(menu);
    }

    /**
     * 修改
     */
    @SysLog("修改菜单")
    @PostMapping("/update")
    @PreAuthorize("@p.check('sys:menu:update')")
    public void update(@RequestBody Menu menu) throws BusinessException {
        Preconditions.checkNotNull(menu.getId(), "菜单ID不能为null");
        // 数据校验
        this.verifyForm(menu);
        this.menuService.updateById(menu);
    }

    /**
     * 删除
     */
    @SysLog("删除菜单")
    @GetMapping("/delete/{menuId}")
    @PreAuthorize("@p.check('sys:menu:delete')")
    public void delete(@PathVariable("menuId") long menuId) throws BusinessException {
        // 判断是否有子菜单或按钮
        List<Menu> menuList = this.menuService.queryListByParentId(menuId);
        if (menuList.size() > 0) {
            throw new BusinessException(BaseExceptionCodes.FAILED, "请先删除子菜单或按钮");
        }
        this.menuService.delete(menuId);
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(Menu menu) throws BusinessException {

        if (StringUtils.isBlank(menu.getName())) {
            throw new BusinessException(BaseExceptionCodes.FAILED, "菜单名称不能为空");
        }

        if (menu.getParentId() == null) {
            throw new BusinessException(BaseExceptionCodes.FAILED, "上级菜单不能为空");
        }

        // 菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                throw new BusinessException(BaseExceptionCodes.FAILED, "菜单URL不能为空");
            }
        }

        // 上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if (menu.getParentId() > 0) {
            Menu parentMenu = this.menuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        // 目录、菜单
        if (menu.getType() == Constant.MenuType.CATALOG.getValue() || menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new BusinessException(BaseExceptionCodes.FAILED, "上级菜单只能为目录类型");
            }
            return;
        }

        // 按钮
        if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new BusinessException(BaseExceptionCodes.FAILED, "上级菜单只能为菜单类型");
            }
        }
        if (menu.getId() != null && menu.getId().equals(menu.getParentId())) {
            throw new BusinessException(BaseExceptionCodes.FAILED, "上级菜单不能选择自己");
        }
    }
}
